package com.scape.core.model;

import org.springframework.roo.addon.entity.RooEntity;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import javax.persistence.Basic;
import javax.persistence.EntityManager;
import javax.persistence.FetchType;
import javax.persistence.Lob;
import javax.persistence.OrderBy;
import javax.persistence.TypedQuery;
import javax.validation.constraints.Size;
import java.util.Set;
import java.util.HashSet;
import javax.persistence.OneToMany;
import javax.persistence.CascadeType;
import javax.persistence.ManyToOne;
import org.springframework.roo.addon.json.RooJson;

@RooJavaBean
@RooToString
@RooEntity(finders = { "findResourcesByParentResource" })
@RooJson(deepSerialize = true)
public class Resource {

    private String title;

    @Size(max = 100)
    private String description;

    @Lob
    @Basic(fetch = FetchType.LAZY)
    private byte[] pic;

    private Boolean isCategory;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "parentResource" , fetch=FetchType.EAGER)
    @OrderBy(value="title")
    private Set<com.scape.core.model.Resource> childResources = new HashSet<com.scape.core.model.Resource>();

    @ManyToOne
    private com.scape.core.model.Resource parentResource;

    private int quantity;

	public static TypedQuery<Resource> findTopLevelResources(){
        EntityManager em = Resource.entityManager();
        TypedQuery<Resource> q = em.createQuery("SELECT o FROM Resource AS o WHERE o.parentResource = null", Resource.class);
         return q;
    }

	public static TypedQuery<Resource> findTopLevelResources(int firstResult, int maxResults) 
	{
        EntityManager em = Resource.entityManager();
        TypedQuery<Resource> q = em.createQuery("SELECT o FROM Resource AS o WHERE o.parentResource = null", Resource.class).setFirstResult(firstResult).setMaxResults(maxResults);
        return q;
    }
}
